package com.jmz.apt.api.Helper;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jmz.apt.api.Utils.JsonSerializerUtil;
import com.jmz.apt.api.Utils.ValidatorBizUtil;
import com.jmz.apt.api.dto.Dto;
import com.jmz.apt.api.dto.impl.AdminUserDto;
import com.jmz.apt.api.entity.IEntity;
import com.jmz.apt.api.enums.ResponseCode;
import com.jmz.apt.api.exception.BusinessException;
import com.jmz.apt.api.message.request.Condition;
import com.jmz.apt.api.message.request.Data;
import com.jmz.apt.api.message.request.RequestMessage;
import com.jmz.apt.api.message.request.RequestMessageTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fanglexue on 2019/11/5.
 */


@Component
public class RequestHelper {

    @Autowired
    ValidatorBizUtil validatorBizUtil;

    /**
     * Convert data into entity.
     * @param requestMessage
     * @return
     */
    public  <T extends IEntity> List<List<T>> mapDataSet(ObjectMapper objectMapper, RequestMessage requestMessage, Class<T> T)  {
        RequestMessageTemplate requestMessageTemplate = new RequestMessageTemplate(requestMessage);
        List<Data> dataSet = requestMessageTemplate.getDataSet();
        List<List<T>> dtoList = new ArrayList<>();
        if (dataSet != null && !dataSet.isEmpty()){
            List<Object> objects = null;
            for (Data data: dataSet){
                objects = data.getRow();
                List<T>  dtoS = new ArrayList<>();
                for (Object obj: objects) {
                    T dto   = objectMapper.convertValue(obj,T);
                    dtoS.add(dto);
                }
                dtoList.add(dtoS);
            }
        }
        return  dtoList;
    }


    public void checkoutCondition(RequestMessage requestMessage,String ruleFile){
        RequestMessageTemplate requestMT = new RequestMessageTemplate(requestMessage);
        List<Condition> conditions = requestMT.getConditions();
        String errorMsg = validatorBizUtil.checkCondition(conditions,ruleFile);
        if(!StringUtils.isEmpty(errorMsg)){
            throw new BusinessException(ResponseCode.LOSE_ARGUMENTS.getCode()
                    ,ResponseCode.LOSE_ARGUMENTS.getDesc());
        }
    }

}
